package cn.epsilon3.utils;

import cn.epsilon3.exception.Epsilon3Exception;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * SpringBean 工具类
 *
 * @author epsilon3
 * @date 2023-05-07
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	/**
	 * 通过name获取 Bean.
	 *
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		Object bean;
		try {
			bean = getApplicationContext().getBean(name);
		} catch (BeansException beansException) {
			throw new Epsilon3Exception("no such as bean named " + name);
		}
		return bean;
	}

	/**
	 * 通过class获取Bean.
	 *
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz) {
		T bean;
		try {
		bean = getApplicationContext().getBean(clazz);
		} catch (BeansException beansException) {
			throw new Epsilon3Exception("no such as bean named " + clazz.getName());
		}
		 return bean;
	}

	/**
	 * 通过name及Clazz返回指定的Bean
	 *
	 * @param name
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

	@Override
	@Autowired
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	/**
	 * 获取applicationContext
	 *
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
}
